package logic

import (
	"fmt"
	"time"

	"erp/model"

	"gorm.io/gorm"
)

type ShipmentService struct{ DB *gorm.DB }

// 创建发货单
func (s ShipmentService) CreateShipment(shipment *model.Shipment) error {
	// 生成送货单号
	if shipment.ShipmentNo == "" {
		shipment.ShipmentNo = s.generateShipmentNo()
	}

	// 设置默认发货日期
	if shipment.ShipmentDate == "" {
		shipment.ShipmentDate = time.Now().Format("2006-01-02")
	}

	// 设置默认状态
	if shipment.Status == "" {
		shipment.Status = "待发货"
	}

	// 验证订单是否存在
	var order model.Order
	if err := s.DB.First(&order, shipment.OrderID).Error; err != nil {
		return fmt.Errorf("订单不存在: %w", err)
	}

	return s.DB.Create(shipment).Error
}

// 获取发货单详情
func (s ShipmentService) GetShipment(id uint) (*model.Shipment, error) {
	var shipment model.Shipment
	if err := s.DB.Preload("Order").First(&shipment, id).Error; err != nil {
		return nil, fmt.Errorf("发货单不存在: %w", err)
	}
	return &shipment, nil
}

// 更新发货状态
func (s ShipmentService) UpdateShipmentStatus(id uint, status string, notes string) error {
	var shipment model.Shipment
	if err := s.DB.First(&shipment, id).Error; err != nil {
		return fmt.Errorf("发货单不存在: %w", err)
	}

	// 验证状态值
	validStatuses := []string{"待发货", "已发货", "运输中", "已送达", "已签收", "已取消"}
	valid := false
	for _, s := range validStatuses {
		if s == status {
			valid = true
			break
		}
	}
	if !valid {
		return fmt.Errorf("无效的发货状态: %s", status)
	}

	shipment.Status = status
	if notes != "" {
		shipment.Notes = notes
	}

	return s.DB.Save(&shipment).Error
}

// 删除发货单
func (s ShipmentService) DeleteShipment(id uint) error {
	var shipment model.Shipment
	if err := s.DB.First(&shipment, id).Error; err != nil {
		return fmt.Errorf("发货单不存在: %w", err)
	}

	return s.DB.Delete(&shipment).Error
}

// 批量创建发货单
func (s ShipmentService) BatchCreateShipments(orderIDs []uint) ([]model.Shipment, error) {
	var shipments []model.Shipment

	return shipments, s.DB.Transaction(func(tx *gorm.DB) error {
		for _, orderID := range orderIDs {
			// 检查是否已存在发货单
			var existingShipment model.Shipment
			if err := tx.Where("order_id = ?", orderID).First(&existingShipment).Error; err == nil {
				continue // 已存在发货单，跳过
			}

			shipment := model.Shipment{
				OrderID:         orderID,
				ShipmentNo:      s.generateShipmentNo(),
				ShipmentDate:    time.Now().Format("2006-01-02"),
				Status:          "待发货",
				DeliveryAddress: "",
				ContactPerson:   "",
				ContactPhone:    "",
				Notes:           "批量创建",
			}

			if err := tx.Create(&shipment).Error; err != nil {
				return err
			}

			shipments = append(shipments, shipment)
		}
		return nil
	})
}

// 获取发货统计
func (s ShipmentService) GetShipmentStats() (map[string]interface{}, error) {
	var stats map[string]interface{} = make(map[string]interface{})

	// 总发货单数
	var totalShipments int64
	if err := s.DB.Model(&model.Shipment{}).Count(&totalShipments).Error; err != nil {
		return nil, err
	}
	stats["total_shipments"] = totalShipments

	// 今日发货数
	var todayShipments int64
	today := time.Now().Format("2006-01-02")
	if err := s.DB.Model(&model.Shipment{}).Where("shipment_date = ?", today).Count(&todayShipments).Error; err != nil {
		return nil, err
	}
	stats["today_shipments"] = todayShipments

	// 待发货数
	var pendingShipments int64
	if err := s.DB.Model(&model.Shipment{}).Where("status = ?", "待发货").Count(&pendingShipments).Error; err != nil {
		return nil, err
	}
	stats["pending_shipments"] = pendingShipments

	// 已发货数
	var shippedCount int64
	if err := s.DB.Model(&model.Shipment{}).Where("status IN ?", []string{"已发货", "运输中", "已送达", "已签收"}).Count(&shippedCount).Error; err != nil {
		return nil, err
	}
	stats["shipped_count"] = shippedCount

	return stats, nil
}

// 生成送货单号
func (s ShipmentService) generateShipmentNo() string {
	now := time.Now()
	dateStr := now.Format("20060102")

	var count int64
	s.DB.Model(&model.Shipment{}).Where("shipment_no LIKE ?", "SH"+dateStr+"%").Count(&count)

	return fmt.Sprintf("SH%s%04d", dateStr, count+1)
}
